package ru.agiledev.aos.core;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import ru.agiledev.aos.commons.dto.SearchEntry;
import ru.agiledev.aos.core.util.Transformer;
import ru.agiledev.aos.data.HibernateUtil;
import ru.agiledev.aos.data.domain.SearchResultDump;
import ru.agiledev.ysearch.YSearch;

import java.io.IOException;
import java.util.List;

/**
 * Created by a.kirillov
 * Date: 2/14/12 Time: 9:52 PM
 */
public class SearchThread extends Thread {
    QueriesRunner runner;
    String query;
    public SearchThread(String query, QueriesRunner runner) {
        this.runner = runner;
        this.query = query;
    }

    @Override
    public void run() {
        List<SearchEntry> results = null;

        String xmlResults = getDump(query);

        if(xmlResults!=null){
            results = Transformer.transform(xmlResults);
        }else {

            YSearch searcher = new YSearch("a-kirillov-a-search-in", "03.75627595:9689e3ecc186de751d138bc36a5a0069");

            try {
                xmlResults = searcher.getSearchResults(query);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if(xmlResults!=null){
                results = Transformer.transform(xmlResults);
            }

            if(results.size()>0){
                writeDump(query, xmlResults);
            }
        }

        runner.registerResult(results);
    }

    private String getDump(String query){
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(SearchResultDump.class).add(Restrictions.eq("query", query));

        List<SearchResultDump> xml = criteria.list();
        if(xml.size() == 0){
            session.close();
            return null;
        } else {
            if(xml.get(0).getXml().length()>0){
                session.close();
                return xml.get(0).getXml();
            } else{
                session.close();
                return null;
            }
        }
    }


    private void writeDump(String query, String xml){
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        SearchResultDump dump = new SearchResultDump(query, xml);

        session.save(dump);
        session.getTransaction().commit();
        session.close();
    }
}
